import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Events } from 'ionic-angular';
import { DeviceProvider } from '../../providers/service/device'
import { PageModel } from '../../models/page'
import { Keyboard } from '@ionic-native/keyboard';
import { BadDetailPage } from './bad-detail/bad-detail';
/**
 * Generated class for the BadPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-bad',
  templateUrl: 'bad.html',
  providers: [Keyboard]
})
export class BadPage {

  constructor(public navCtrl: NavController,
    public deviceProvider: DeviceProvider,
    public keyboard: Keyboard,
    public events: Events,
    public navParams: NavParams) {

        //订阅项目更新
        events.subscribe('RF_BAD_ITEM', (res)=>{
            this.list.map((v,idx)=>{
                if(v.id ==res.id){
                    this.list[idx] = res;
                }
            })
        })

  }

  isReady = false;
  isLoading = true;
  pageObj = new PageModel();
  searchKey = '';
  list = []

  ionViewDidLoad() {
    // console.log('ionViewDidLoad DevicePage');
    this.isReady = true;
    this.getDataList(true);
    // pageSize    : 10,
    // pageNum     : 1,
    // total       : 1,
    // timeRange   : '',    //时间范围
    // physicalCode: '', //序列号
    // status      : ''     //设备状态

  }

  /**
   * 下拉刷新
   * @param refresher
   */
  doRefresh(refresher) {
    this.getDataList(true).then(() => {
      refresher.complete();
    })
  }

  /**
   * 上拉加载
   * @param infiniteScroll
   */
  doInfinite(infiniteScroll) {
    this.getDataList().then(() => {
      infiniteScroll.complete();
    })
  }

  //搜索
  searchOnHandler() {
    this.getDataList(true);
  }

  //搜索取消
  searchOnCancel(event) {
    event.stopPropagation();
    this.searchOnHandler();
    setTimeout(function () {
      console.log(this.keyboard)
      try {
        this.keyboard || this.keyboard.close(); //关闭keyboard
      } catch (e) { }
      event.target.blur();
    }, 500);
  }

  getDataList(isRefresh = false) {
    this.isLoading = true;
    if (isRefresh) {
      this.pageObj.pageNum = 1;
      this.list = [];
    }

    let elseFilter = {
        physicalCode: this.searchKey
    }

    return this.deviceProvider.getBadList({ ...this.pageObj, ...elseFilter }).then((res: any) => {
      console.log(res)
      this.pageObj.pageSize = res.pageSize;
      this.pageObj.pageNum = res.pageNum;
      this.pageObj.total = res.total;
      this.pageObj.isLastPage = res.isLastPage;
      this.pageObj.pageNum++;
      this.isLoading = false;
      this.list = this.list.concat(res.list);
  
    }, err => {
      this.isLoading = false;
    });

  }

  pToDetail(item){
    this.navCtrl.push(BadDetailPage, {id: item.id});
  }

}
